package com.ceres.login.service.impl;


import com.ceres.login.dao.UserMapper;
import com.ceres.login.pojo.User;
import com.ceres.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.bcrypt.BCrypt;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * @param username
     * @param password
     * @return
     */
    @Override
    public int login(String username, String password) {
        //根据登录名获取管理员信息
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        User userResult = userMapper.selectOneByExample(example);
        //获取redis中对String字符串操作的对象
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        //boos为判断redis中是否有此key存在
        Boolean boos;
        String keyword="user"+userResult.getUsername();

        //判断用户是否存在
        //查询结果为空，或者用户状态为2(2:被逻辑删除（不存在）)
        if (userResult == null || userResult.getStatus().equals("2")) {
            // 用户不存在
            return 2;
        } else {
            //判断账号状态 0:被锁定，1:启用
            //账号被锁定
            if (userResult.getStatus().equals("0")) {
                return 3;
            } else {
                if (userMapper.findDateByusername(username).before(new Date())) {
                    //判断时间是否过期
                    return 5;
                }
                //对密码进行校验
                boolean boo = BCrypt.checkpw(password, userResult.getPassword());
                //密码正确
                if (boo) {
                    //如果密码相同，则看redis中是否有错误次数，如果有则删除
                    boos = redisTemplate.hasKey(keyword);
                    if (boos) {
                        redisTemplate.delete(keyword);
                    }
                    //初次登录判断
                    //判断密码是不是123456
                    if (BCrypt.checkpw("123456", userResult.getPassword())) {
                        //判断是否是管理员
                        if (userMapper.findRoleByUsername(username).contains(2)) {
                            return 1;
                        } else {
                            return 4;
                        }
                    } else {
                        return 1;
                    }
                }
                //密码错误
                else {
                    //验证此key是否存在
                    boos = redisTemplate.hasKey(keyword);
                    if (boos) {
                        //如果boos为true,则证明redis中有此key,获取key的数值并加1
                        Integer inte = Integer.parseInt(valueOperations.get(keyword));
                        inte++;
                        valueOperations.set(keyword, inte + "");
                    } else {
                        //boos为flase,则证明redis中没有此key,密码是第一次错误,故走以下逻辑
                        valueOperations.set(keyword, 1 + "");
                        //redis中设置key的过期时间 30分钟
                        redisTemplate.expire(keyword, 1800, TimeUnit.SECONDS);
                    }
                    //判断错误次数,大于等于5次锁定
                    if (Integer.parseInt(valueOperations.get(keyword)) >= 5) {
                        //锁定用户
                        userMapper.editUserStatus(username);
                    }
                    return 2;
                }
            }

        }
    }
    @Override
    public User findByUsername(String username){
        //根据登录名获取管理员信息
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        return  userMapper.selectOneByExample(example);
    }

    @Override
    public void editUserStatus(String username) {
        userMapper.editUserStatus(username);
    }

    @Override
    public List<Integer> findRoleByUsername(String username) {
        return userMapper.findRoleByUsername(username);
    }

    @Override
    public Date findDateByusername(String username) {
        return userMapper.findDateByusername(username);
    }
}


